`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 11/06/2021 11:12:27 AM
// Design Name: 
// Module Name: key_last_control
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module key_last_control(
    input clk,
    input rst_n,
    input key_p_flag,
    input key_n_flag,
    output reg key_value,
    output reg last
    );
    reg ispose;
    parameter LASTING_COUNT = 50000000;
    reg [30:0] count;
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            ispose <= 0;
        end
        else begin
            if (key_p_flag) begin
                ispose <= 1;
            end
            else if (key_n_flag)
                ispose <= 0;
        end
    end
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            count <= LASTING_COUNT;
        end
        else begin
            if (ispose && count > 0)
                count <= count - 1;
            else if(ispose && count==0)
                count <= 0;
            else
                count <= LASTING_COUNT;
        end
    end
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            key_value <= 0;
            last <= 0;
        end
        else begin
            if (key_n_flag==1 && count>0) begin
                key_value <= 1;
                last <= 0;
            end
            else if(count ==0) begin
                key_value <= 0;
                last <= 1;
            end
            else begin
                key_value <=0;
                last <= 0;
            end
        end
            
    end
endmodule
